
const jwt = require('jsonwebtoken')

const { JWT_SECRET } = require('../config/config_default')

const { tokenExpireError, invlidToken, handNotAdminPermission } = require('../constant/error_type')


//校验token
const auth = async (ctx, next) => {

    // console.log(ctx);


    const { authorization = '' } = ctx.request.header

    const token = authorization.replace('Bearer ', '')


    try {
        //验证成功就返回包含playload的信息(id,user_name,is_admin)
        const user = jwt.verify(token, JWT_SECRET)

        ctx.state.user = user

    } catch (error) {
        // console.log(error);

        switch (error.name) {
            case 'TokenExpiredError':
                console.error('token已过期', error);
                ctx.app.emit('error', tokenExpireError, ctx)
                return
            case 'JsonWebTokenError':
                console.error('无效的token', error);
                ctx.app.emit('error', invlidToken, ctx)
                return
        }
    }

    await next();
}


//是否管理员权限
const handAdminPermission = async (ctx, next) => {
    // console.log(ctx.state.user);

    const { IsAdmin } = ctx.state.user

    if (!IsAdmin) {
        console.error('该用户没有管理员权限');
        return ctx.app.emit('error', handNotAdminPermission, ctx)
    }
    await next();
}

module.exports = {
    auth, handAdminPermission
}